﻿using DataInit.DataContexts;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace IncidentSvc.Services
{
    public class IncidentService : Incident.IncidentBase
    {
        private readonly ILogger _logger;
        private readonly PTDBContext pTDBContext;
        public IncidentService(ILogger<IncidentService> logger, PTDBContext pTDBContext)
        {
            this._logger = logger;
            this.pTDBContext = pTDBContext;
        }

        public override Task<IncidentReply> GetIncidents(IncidentRequest request, ServerCallContext context)
        {
            var result = new IncidentReply
            {
                Result = new Result
                {
                    Message = "暂无数据"
                }
            };
            //获取列表

            if (!string.IsNullOrEmpty(request.IncNos))
            {
                var ids = request.IncNos.Split(';', StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    using (this.pTDBContext)
                    {
                        var list = this.pTDBContext.IncidentEntity
                               .Where(s => s.Status == DataInit.Entities.IncidentState.Open && ids.Contains(s.IncidentNumber.ToString()))
                               .Select(s => new
                               {
                                   s.IncidentNumber,
                                   s.GroupId,
                                   s.OperatorId,
                                   s.Status
                               });
                        
                        result.Result.Succeed = true;
                        result.Result.Message = "ok";
                        result.Data = JsonSerializer.Serialize(list);
                        this._logger.LogWarning(result.Data);
                    }
                }
                catch (Exception ex)
                {
                    this._logger.LogError(ex.Message);
                    result.Result.Message = ex.Message;
                }
            }

            return Task.FromResult(result);
        }


    }
}
